package com.cloudfun.campusshare.service.impl;

import com.cloudfun.campusshare.common.constant.AsyncTaskBizType;
import com.cloudfun.campusshare.common.constant.AsyncTaskStatus;
import com.cloudfun.campusshare.common.model.dto.AsyncTaskDTO;
import com.cloudfun.campusshare.entity.DeviceAlarmEntity;
import com.cloudfun.campusshare.entity.DeviceEntity;
import com.cloudfun.campusshare.repo.DeviceAlarmRepo;
import com.cloudfun.campusshare.repo.DeviceEntityRepo;
import com.cloudfun.campusshare.service.AsyncTaskService;
import com.cloudfun.campusshare.service.DeviceAlarmService;
import com.cloudfun.msgsubscribe.DeviceInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

/**
 * Created by Huqin on 2019/12/26
 */
@Slf4j
@Service
public class DeviceAlarmServiceImpl implements DeviceAlarmService {

    @Autowired
    private DeviceAlarmRepo deviceAlarmRepo;

    @Autowired
    private DeviceEntityRepo deviceEntityRepo;

    @Autowired
    private AsyncTaskService asyncTaskService;

    @Override
    @Transactional
    public void onAlarm(String imei, String alarmName) {
        if (StringUtils.isBlank(alarmName)) {
            return;
        }
        DeviceEntity deviceEntity = deviceEntityRepo.findByImei(imei);
        if (Objects.isNull(deviceEntity)) {
            return;
        }
        // 设备测试任务状态更新
        List<AsyncTaskDTO> asyncTaskDTOList = asyncTaskService.getRunnable(AsyncTaskBizType.DEVICE_RELIABILITY, deviceEntity.getId());
        if (!CollectionUtils.isEmpty(asyncTaskDTOList)) {
            asyncTaskDTOList.addAll(asyncTaskService.getRunnable(AsyncTaskBizType.DEVICE_INFINITY_LOOP, deviceEntity.getId()));
            for (AsyncTaskDTO asyncTaskDTO : asyncTaskDTOList) {
                log.info("设备：{}下线，设备测试任务: {}中断", deviceEntity.getId(), asyncTaskDTO.getId());
                asyncTaskDTO.setStatus(AsyncTaskStatus.ERROR_CANCEL);
                asyncTaskService.modify(asyncTaskDTO);
            }
        }

        // 保存告警
        DeviceAlarmEntity alarmEntity = deviceAlarmRepo.findByDeviceIdAndAlarmName(deviceEntity.getId(), alarmName);
        if (null == alarmEntity) {
            alarmEntity = DeviceAlarmEntity.builder()
                    .alarmName(alarmName)
                    .deviceId(deviceEntity.getId())
                    .valid(true)
                    .build();
        }
        alarmEntity.setValid(true);
        deviceAlarmRepo.save(alarmEntity);
    }

    @Override
    @Transactional
    public void onAlarmCancel(String imei) {
        DeviceEntity deviceEntity = deviceEntityRepo.findByImei(imei);
        if (Objects.isNull(deviceEntity)) {
            return;
        }
        List<DeviceAlarmEntity> deviceAlarmEntities = deviceAlarmRepo.findAllByDeviceIdAndValid(deviceEntity.getId(), true);
        if (CollectionUtils.isEmpty(deviceAlarmEntities)) {
            return;
        }
        deviceAlarmEntities.forEach(deviceAlarmEntity -> deviceAlarmEntity.setValid(false));
        deviceAlarmRepo.saveAll(deviceAlarmEntities);
    }

    @Override
    public void onAlarm(DeviceInfo deviceInfo) {
        if (deviceInfo.getAlarms().contains("alarmCancel")) {
            this.onAlarmCancel(deviceInfo.getImei());
        } else {
            for (String alarmName : deviceInfo.getAlarms()) {
                this.onAlarm(deviceInfo.getImei(), alarmName);
            }
        }
    }
}
